﻿Imports LullabyFullDeCaixa.Web
Imports System.ServiceModel.DomainServices.Client.ApplicationServices
Imports System.ServiceModel.DomainServices.Client
Imports System.Collections.ObjectModel

Partial Public Class Home
    Inherits Page

#Region "Crear i destruir"
    Public Sub New()
        InitializeComponent()

        AddHandler Contexte.AutomaticLoadStep, AddressOf AutomaticLoadStep
    End Sub

    Private Sub Home_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Me.Components.Visibility = Windows.Visibility.Collapsed

        If Not Contexte.IsHostalsLoaded OrElse Not Contexte.IsTipusDespesaIngresLoaded OrElse Not Contexte.IsUsuarisLoaded Then
            Me.ActivityFullDeCaixa.IsActive = True
        End If

        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then

        ElseIf Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Recepcionista Then
            Me.btnOpcions.Visibility = Windows.Visibility.Collapsed
            Me.lnOpcions.Visibility = Windows.Visibility.Collapsed
            Me.btnInformes.Visibility = Windows.Visibility.Collapsed
            Me.lnInformes.Visibility = Windows.Visibility.Collapsed

            Me.btnModificarNeteja.Visibility = Windows.Visibility.Collapsed

            Me.btnHorarios.IsEnabled = False

            Dim DataInicial As Date = New Date(Now.Year, Now.Month, 1, 0, 0, 0, 0, DateTimeKind.Utc)

            LullabyFullDeCaixa.Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetDocumentsPerHostalIDatesQuery(Contexte.HostalActual.Id, DataInicial.AddMonths(-1), DataInicial.AddMonths(1)), LoadBehavior.RefreshCurrent, _
               New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.Document))(AddressOf DocumentLoaded), _
               Nothing)
        ElseIf Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Neteja Then
            'Neteja
            Me.btnOpcions.Visibility = Windows.Visibility.Collapsed
            Me.lnOpcions.Visibility = Windows.Visibility.Collapsed
            Me.btnInformes.Visibility = Windows.Visibility.Collapsed
            Me.lnInformes.Visibility = Windows.Visibility.Collapsed

            Me.btnModificarNeteja.Visibility = Windows.Visibility.Collapsed

            Me.ActivityFullDeCaixa.Visibility = Windows.Visibility.Collapsed
            Me.grdNeteja.Visibility = Windows.Visibility.Collapsed
            Me.grdNotes.Visibility = Windows.Visibility.Collapsed
        Else
            'Manager
            Me.btnOpcions.Visibility = Windows.Visibility.Collapsed
            Me.lnOpcions.Visibility = Windows.Visibility.Collapsed
            Me.btnModificarNeteja.Visibility = Windows.Visibility.Collapsed
        End If

        Me.grdBuscador.ItemsSource = DadesBuscador
    End Sub

    Private Sub Home_Unloaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Unloaded
        RemoveHandler Contexte.AutomaticLoadStep, AddressOf AutomaticLoadStep
        'tmrRefresc.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
        'tmrRefresc.Dispose()
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()

        'RefreshTimer.Dispose()
    End Sub

    Private Sub AutomaticLoadStep(ByVal Item As Integer)
        If Item <= Contexte.MAX_ITEM_LOAD_STEP Then
            App.ShowInfo(String.Format(StringLibrary.InfoCarregantDades, Item, Contexte.MAX_ITEM_LOAD_STEP))
        End If

        If Contexte.IsHostalsLoaded AndAlso Contexte.IsTipusDespesaIngresLoaded AndAlso Contexte.IsUsuarisLoaded Then
            Me.ActivityFullDeCaixa.IsActive = False
            OmpleDadesBuscador()
            BuscaNotes(True)
            BuscaNeteges(True)
        End If
    End Sub
#End Region

#Region "Notes"
    Private Sub BuscaNotes(MostrarBarraProgrés As Boolean)

        Me.ActivityNotes.IsActive = MostrarBarraProgrés

        Dim DataInicial As Date = Date.SpecifyKind(Now.Date, DateTimeKind.Utc)

        LullabyFullDeCaixa.Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetNotesNoCaducadesPerUsuariQuery(Contexte.UsuariActual.Id, DataInicial), LoadBehavior.RefreshCurrent, _
           New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.Nota))(AddressOf NotesLoaded), _
           Nothing)
    End Sub

    Private Sub NotesLoaded(ByVal LListaNotes As LoadOperation(Of LullabyFullDeCaixa.Web.Nota))
        'Un cop carregat ho guardem en una llista
        Me.ActivityNotes.IsActive = False
        Me.lstNotes.ItemsSource = (From N As Nota In LListaNotes.Entities Order By N.Data Descending, N.Id Descending).ToList()
    End Sub

    Private Sub btnAltaNota_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As DetallGestioNotes = New DetallGestioNotes(DetallGestioNotes.EnumMode.ModeAlta, New Web.Nota())
        AddHandler Child.Closed, AddressOf ChildNota_Closed
        Child.Show()
    End Sub

    Private Sub ChildNota_Closed(sender As Object, e As EventArgs)
        RemoveHandler DirectCast(sender, DetallGestioNotes).Closed, AddressOf ChildNota_Closed
        Me.lstNotes.ItemsSource = (From N As Nota In Contexte.DomainContext.Notas Order By N.Data Descending, N.Id Descending).ToList()
    End Sub

    Private Sub btnModificarNota_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As DetallGestioNotes = New DetallGestioNotes(DetallGestioNotes.EnumMode.ModeModificacio, DirectCast(lstNotes.SelectedItem, Nota))
        Child.Show()
    End Sub
    Private Sub btnEliminarNota_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Try
            If (MessageBox.Show(StringLibrary.DeleteConfirm & vbNewLine, StringLibrary.DeleteTitol, MessageBoxButton.OKCancel) = MessageBoxResult.OK) Then
                Contexte.DomainContext.Notas.Remove(Me.lstNotes.SelectedItem)
                Contexte.DomainContext.SubmitChanges(AddressOf NotaDeleted, Nothing)
                ActivityNotes.IsActive = True
            End If
        Catch ex As Exception
            App.ShowMessage(ex)
            Contexte.DomainContext.RejectChanges()
        End Try
    End Sub

    Private Sub NotaDeleted(ByVal s As SubmitOperation)
        ActivityNotes.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.NoPotBorrar)
            Contexte.DomainContext.RejectChanges()
        Else
            Me.lstNotes.ItemsSource = (From N As Nota In Contexte.DomainContext.Notas Order By N.Data Descending, N.Id Descending).ToList()
        End If
    End Sub

    Private Sub lstNotes_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs)
        If e.AddedItems.Count = 0 Then
            Me.btnEliminarNota.IsEnabled = False
            Me.btnModificarNota.IsEnabled = False
        Else
            Dim Nota As Nota = DirectCast(e.AddedItems(0), Nota)
            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Or Contexte.UsuariActual.Id = Nota.IdUsuariCreador Then
                Me.btnEliminarNota.IsEnabled = True
                Me.btnModificarNota.IsEnabled = True
            Else
                Me.btnEliminarNota.IsEnabled = False
                Me.btnModificarNota.IsEnabled = False
            End If
        End If
    End Sub



#End Region

#Region "Document"
    Private DocumentAnterior As Document
    Private DocumentPosterior As Document
    Private DocumentActual As Document

    Private Sub DocumentLoaded(ByVal LListaDocuments As LoadOperation(Of LullabyFullDeCaixa.Web.Document))
        'Un cop carregat ho guardem en una llista
        Dim Data As Date = New Date(Now.Year, Now.Month, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMonths(-1)
        DocumentAnterior = (From D As Document In LListaDocuments.Entities Where D.DataInicial = Data).FirstOrDefault()
        Data = Data.AddMonths(1)
        DocumentActual = (From D As Document In LListaDocuments.Entities Where D.DataInicial = Data).FirstOrDefault()
        Data = Data.AddMonths(1)
        DocumentPosterior = (From D As Document In LListaDocuments.Entities Where D.DataInicial = Data).FirstOrDefault()

        If DocumentAnterior Is Nothing Then btnMesAnterior.Visibility = Windows.Visibility.Collapsed
        If DocumentActual Is Nothing Then btnMesActual.Visibility = Windows.Visibility.Collapsed
        If DocumentPosterior Is Nothing Then btnMesSiguiente.Visibility = Windows.Visibility.Collapsed

        If DocumentAnterior IsNot Nothing Then btnMesAnterior.Title = DocumentAnterior.Titol
        If DocumentActual IsNot Nothing Then btnMesActual.Title = DocumentActual.Titol
        If DocumentPosterior IsNot Nothing Then btnMesSiguiente.Title = DocumentPosterior.Titol

        If LListaDocuments.Entities.Count > 0 Then btnHorarios.IsEnabled = True
    End Sub
#End Region

#Region "Timer refresca dades"
    'Private tmrRefresc As System.Threading.Timer = New System.Threading.Timer(AddressOf TimerRefresc, Nothing, 60000, 60000)

    'Sub TimerRefresc(State As Object)
    '    'Refresquem les notes
    '    Deployment.Current.Dispatcher.BeginInvoke(New Action(Of Boolean)(AddressOf BuscaNotes), {False})

    '    'Refresquem les neteges
    '    Deployment.Current.Dispatcher.BeginInvoke(New Action(Of Boolean)(AddressOf BuscaNeteges), {False})

    '    'Refresquem els fulls de caixa
    '    Deployment.Current.Dispatcher.BeginInvoke(New Action(Of Boolean)(AddressOf BuscaFullsDeCaixa), {False})
    'End Sub

    Private Sub RefreshNota_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles RefreshNota.Click
        BuscaNotes(True)
    End Sub

    Private Sub RefreshNeteja_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles RefreshNeteja.Click
        BuscaNeteges(True)
    End Sub

    Private Sub RefreshFullDeCaixa_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles RefreshFullDeCaixa.Click
        grdBuscador.SelectedItem = Nothing
        BuscaFullsDeCaixa(True)
    End Sub

#End Region

#Region "Buscador"

    Private DadesBuscador As ObservableCollection(Of LLibreCaixa) = New ObservableCollection(Of LLibreCaixa)

    Private Sub Buscador_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        BuscaFullsDeCaixa(True)
    End Sub

    Private Sub OmpleDadesBuscador()
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Dim LListaHostals As List(Of Hostal) = Contexte.Hostals.ToList
            LListaHostals.Insert(0, New Hostal() With {.Id = -1, .Nom = ""})
            Me.cboHostals.ItemsSource = LListaHostals

            Dim LListaUsuaris As List(Of Usuari) = (From U As LullabyFullDeCaixa.Web.Usuari In Contexte.Usuaris Where U.IdTipusUsuari <> EnumTipusUsuari.Neteja).ToList
            LListaUsuaris.Insert(0, New Usuari() With {.Id = -1, .Nom = ""})
            Me.cboUsuaris.ItemsSource = LListaUsuaris
        Else
            Me.cboHostals.ItemsSource = Contexte.HostalsPerUsuariActual
            Me.cboUsuaris.ItemsSource = {Contexte.UsuariActual}
        End If

        Me.cboHostals.SelectedItem = cboHostals.Items(0)
        Me.cboUsuaris.SelectedItem = cboUsuaris.Items(0)
        Me.dtpDataInicial.SelectedDate = Today.AddDays(-7).ToShortDateString
        Me.dtpDataFinal.SelectedDate = Today.ToShortDateString

        BuscaFullsDeCaixa(True)
    End Sub

    Private Sub BuscaFullsDeCaixa(MostrarBarraProgrés As Boolean)
        Me.ActivityBuscador.IsActive = MostrarBarraProgrés

        Dim DataInicial As Date?
        Dim DataFinal As Date?

        DataInicial = Me.dtpDataInicial.SelectedDate
        If DataInicial.HasValue Then DataInicial = Date.SpecifyKind(DataInicial.Value.Date, DateTimeKind.Utc)

        DataFinal = Me.dtpDataFinal.SelectedDate
        If DataFinal.HasValue Then DataFinal = Date.SpecifyKind(DataFinal.Value.Date, DateTimeKind.Utc)

        LullabyFullDeCaixa.Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetFullsDeCaixaPerHostalUsuariIDatesQuery(DirectCast(Me.cboHostals.SelectedItem, Hostal).Id, DirectCast(Me.cboUsuaris.SelectedValue, Usuari).Id, DataInicial, DataFinal), _
            LoadBehavior.RefreshCurrent, _
            New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.LLibreCaixa))(AddressOf LLibresCaixaLoaded), _
            Nothing)
    End Sub

    Private Sub LLibresCaixaLoaded(ByVal LListaLLibresCaixa As LoadOperation(Of LullabyFullDeCaixa.Web.LLibreCaixa))
        'Un cop carregat ho guardem en una llista
        Me.ActivityBuscador.IsActive = False

        'Afegim els nous
        For Each LLibre As LLibreCaixa In (From LL As LLibreCaixa In LListaLLibresCaixa.Entities Order By LL.Data Descending, LL.IdHostal).ToList()
            If Not DadesBuscador.Contains(LLibre) Then DadesBuscador.Insert(0, LLibre)
        Next

        'Traiem els vells
        Dim LLibresATreure As List(Of LLibreCaixa) = New List(Of LLibreCaixa)
        For Each LLibre As LLibreCaixa In DadesBuscador
            If Not LListaLLibresCaixa.Entities.Contains(LLibre) Then LLibresATreure.Add(LLibre)
        Next

        For Each LLibre As LLibreCaixa In LLibresATreure
            DadesBuscador.Remove(LLibre)
        Next

        DadesBuscador = New ObservableCollection(Of LLibreCaixa)(DadesBuscador.OrderBy(Function(f) f.IdHostal).OrderByDescending(Function(f) f.Data).ToList)

        Me.grdBuscador.ItemsSource = DadesBuscador '.OrderBy(Function(f) f.IdHostal).OrderByDescending(Function(f) f.Data).ToList

    End Sub
#End Region

#Region "Menus"
    Private Sub btnLogout_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim LogOperation As LogoutOperation = DirectCast(RiaContext.Current.Authentication, FormsAuthentication).Logout(New Action(Of LogoutOperation)(AddressOf LogoutOperation_Complete), Nothing)
    End Sub

    Private Sub LogoutOperation_Complete(ByVal LogOperation As LogoutOperation)
        If LogOperation.HasError Then
            'Hi ha hagut una excepcio
            Deployment.Current.Dispatcher.BeginInvoke(New Action(Of String)(AddressOf App.ReportError), StringLibrary.ErrorTancantSessio)
        Else
            'Ha anat bé
            Contexte.Finalitzar()
            DirectCast(App.Current, App).Navigate(New Uri("/Login", UriKind.Relative))
            'RefreshTimer.Change(Timeout.Infinite, Timeout.Infinite)
        End If
    End Sub

    Private Sub btnOpcions_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        popupOpcions.IsOpen = True
    End Sub

    Private Sub LayoutRoot_MouseLeftButtonDown(sender As Object, e As System.Windows.Input.MouseButtonEventArgs) Handles LayoutRoot.MouseLeftButtonDown
        popupOpcions.IsOpen = False
        popupLimpieza.IsOpen = False
        popupHorarios.IsOpen = False
    End Sub

    Private Sub btnOpcions_LostFocus(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnOpcions.LostFocus
        popupOpcions.IsOpen = False
    End Sub

    Private Sub btnCategoriesThingsToDo_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnCategoriesThingsToDo.MouseLeftButtonUp
        Dim child As New DetallGestioCategoriaThingsToDo()
        child.Show()
        popupOpcions.IsOpen = False
    End Sub

    Private Sub btnDespeses_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnDespeses.MouseLeftButtonUp
        Dim child As New DetallGestioTipusDespesaIngres(DetallGestioTipusDespesaIngres.EnumMode.GestioDespeses)
        child.Show()
        popupOpcions.IsOpen = False
    End Sub

    Private Sub btnHostals_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnHostals.MouseLeftButtonUp
        Dim child As New DetallGestioHostals()
        child.Show()
        popupOpcions.IsOpen = False
    End Sub

    Private Sub btnIngressos_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnIngressos.MouseLeftButtonUp
        Dim child As New DetallGestioTipusDespesaIngres(DetallGestioTipusDespesaIngres.EnumMode.GestioIngressos)
        child.Show()
        popupOpcions.IsOpen = False
    End Sub

    Private Sub btnGestioUsuaris_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim child As New DetallGestioUsuaris()
        child.Show()
    End Sub

    Private Sub btnThingsToDo_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim child As New DetallGestioThingsToDo()
        child.Show()
    End Sub

    Private Sub btnInformes_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim child As New GestorReports()
        child.Show()
    End Sub

    Private Sub btnHorarios_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador OrElse Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Manager Then
            Dim child As New DetallGestioDocuments()
            child.Show()
        Else
            popupHorarios.IsOpen = True
        End If
    End Sub

    Private Sub btnHorarios_LostFocus(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnHorarios.LostFocus
        popupHorarios.IsOpen = False
    End Sub

    Private Sub btnMesAnterior_LostFocus(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnMesAnterior.LostFocus
        Dim uri As String = "/Documents/" + DocumentAnterior.Id.ToString() + "_" + DocumentAnterior.FileName
        System.Windows.Browser.HtmlPage.Window.Eval("window.open('" & uri & "', '_blank')")

        popupHorarios.IsOpen = False
    End Sub

    Private Sub btnMesSiguiente_LostFocus(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnMesSiguiente.LostFocus
        Dim uri As String = "/Documents/" + DocumentPosterior.Id.ToString() + "_" + DocumentPosterior.FileName
        System.Windows.Browser.HtmlPage.Window.Eval("window.open('" & uri & "', '_blank')")

        popupHorarios.IsOpen = False
    End Sub

    Private Sub btnMesActual_LostFocus(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnMesActual.LostFocus
        Dim uri As String = "/Documents/" + DocumentActual.Id.ToString() + "_" + DocumentActual.FileName
        System.Windows.Browser.HtmlPage.Window.Eval("window.open('" & uri & "', '_blank')")

        popupHorarios.IsOpen = False
    End Sub

    Private Sub btnLimpieza_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Dim child As New DetallGestioNeteja()
            child.Show()
        Else
            popupLimpieza.IsOpen = True
        End If
    End Sub

    Private Sub btnLimpieza_LostFocus(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnLimpieza.LostFocus
        popupLimpieza.IsOpen = False
    End Sub

    Private Sub btnEntrada_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnEntrada.MouseLeftButtonUp
        Dim child As New NetejaEntradaSortida(NetejaEntradaSortida.EnumMode.ModeEntrada)
        child.Show()

        popupLimpieza.IsOpen = False
    End Sub

    Private Sub btnSortida_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnSortida.MouseLeftButtonUp
        Dim child As New NetejaEntradaSortida(NetejaEntradaSortida.EnumMode.ModeSortida)
        child.Show()

        popupLimpieza.IsOpen = False
    End Sub

#End Region

#Region "Full De Caixa"

    Private Sub EliminarFullDeCaixa_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles EliminarFullDeCaixa.Click
        Try
            If (MessageBox.Show(StringLibrary.DeleteConfirm & vbNewLine, StringLibrary.DeleteTitol, MessageBoxButton.OKCancel) = MessageBoxResult.OK) Then
                Contexte.DomainContext.LLibreCaixas.Remove(grdBuscador.SelectedItem)
                Contexte.DomainContext.SubmitChanges(AddressOf NodeDeleted, Nothing)
                ActivityBuscador.IsActive = True
            End If
        Catch ex As Exception
            App.ShowMessage(ex)
            Contexte.DomainContext.RejectChanges()
        End Try
    End Sub

    Private Sub NodeDeleted(ByVal s As SubmitOperation)
        ActivityBuscador.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.NoPotBorrar)
            Contexte.DomainContext.RejectChanges()
        Else
            For Each E As Entity In s.ChangeSet.RemovedEntities
                If TypeOf E Is LLibreCaixa Then
                    DadesBuscador.Remove(E)
                End If
            Next
        End If
    End Sub

    Private Sub AfegirFullDeCaixa_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles AfegirFullDeCaixa.Click
        Dim Child As FullDeCaixaAltaModificacio = New FullDeCaixaAltaModificacio(FullDeCaixaAltaModificacio.EnumMode.ModeAlta, New LLibreCaixa() With {.ControlarLLibreObertAnterior = True})
        AddHandler Child.Closed, AddressOf AfegirFullDeCaixa_Closed
        Child.Show()
    End Sub

    Private Sub AfegirFullDeCaixa_Closed(sender As Object, e As EventArgs)
        Dim Child As FullDeCaixaAltaModificacio = DirectCast(sender, FullDeCaixaAltaModificacio)

        RemoveHandler Child.Closed, AddressOf AfegirFullDeCaixa_Closed

        If Child.DialogResult.HasValue AndAlso Child.DialogResult.Value Then
            Me.DadesBuscador.Add(Child.LLibreCaixa)
            Me.grdBuscador.SelectedItem = Child.LLibreCaixa
        End If
    End Sub

    Private Sub grdBuscador_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdBuscador.SelectionChanged

        If e.AddedItems.Count = 0 Then
            Me.EliminarFullDeCaixa.IsEnabled = False
            Me.Components.Visibility = Windows.Visibility.Collapsed
        Else
            Dim FullSeleccionat As LLibreCaixa = DirectCast(e.AddedItems(0), LLibreCaixa)
            ProtegirFullDeCaixa(FullSeleccionat)

            ActualitzarDadesGridDespesaIngres()
            ActualitzarDadesGridReserves()
            ProtegirGridReserves(False)
            ProtegirGridDespesesIngressos(False)
        End If
    End Sub

    Private Sub ProtegirFullDeCaixa(FullSeleccionat As LLibreCaixa)

        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Me.EliminarFullDeCaixa.IsEnabled = True
            Me.btnFullDeEditar.IsEnabled = True
            Me.btnTancamentEditar.IsEnabled = True
            Me.btnFullDeCaixaTancar.IsEnabled = Not FullSeleccionat.EsTancat
        ElseIf Not FullSeleccionat.EsTancat Then
            Me.EliminarFullDeCaixa.IsEnabled = False 'Només poden eliminar els administradors
            Me.btnFullDeEditar.IsEnabled = True
            Me.btnFullDeCaixaTancar.IsEnabled = True
            Me.btnTancamentEditar.IsEnabled = True
        Else
            Me.btnFullDeEditar.IsEnabled = False
            Me.btnFullDeCaixaTancar.IsEnabled = False
            Me.EliminarFullDeCaixa.IsEnabled = False
            Me.btnTancamentEditar.IsEnabled = False
        End If

        Me.Components.Visibility = Windows.Visibility.Visible
    End Sub


    Private Sub btnEditar_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As FullDeCaixaAltaModificacio = New FullDeCaixaAltaModificacio(FullDeCaixaAltaModificacio.EnumMode.ModeModificacio, grdBuscador.SelectedItem)
        Child.Show()
    End Sub

    Private Sub btnFullDeCaixaTancar_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim LLibre As LLibreCaixa = DirectCast(grdBuscador.SelectedItem, LLibreCaixa)

        If LLibre.EstatRecepcioInici.HasValue AndAlso LLibre.EstatBanyInici.HasValue AndAlso LLibre.EstatSalaInici.HasValue AndAlso _
            LLibre.EstatCuinaInici.HasValue AndAlso LLibre.EstatPassadisInici.HasValue AndAlso LLibre.EstatTerrassaInici.HasValue AndAlso _
            LLibre.EstatRecepcioFinal.HasValue AndAlso LLibre.EstatBanyFinal.HasValue AndAlso LLibre.EstatSalaFinal.HasValue AndAlso _
            LLibre.EstatCuinaFinal.HasValue AndAlso LLibre.EstatPassadisFinal.HasValue AndAlso LLibre.EstatTerrassaFinal.HasValue Then

            Dim inputMessage As InputWindow = New InputWindow(StringLibrary.TancamentConfirm, InputWindow.EnumTipus.PasswordBox)

            AddHandler inputMessage.Closed, AddressOf VerificarTancament
            inputMessage.Show()
        Else
            MessageBox.Show(StringLibrary.DadesHostalIncorrectes & vbNewLine, StringLibrary.ErrorTancament, MessageBoxButton.OK)
            Dim Child As FullDeCaixaTancament
            Child = New FullDeCaixaTancament(grdBuscador.SelectedItem)
            Child.Show()
        End If


    End Sub

    Private Sub VerificarTancament(sender As System.Object, e As System.EventArgs)
        RemoveHandler DirectCast(sender, InputWindow).Closed, AddressOf VerificarTancament

        If DirectCast(sender, InputWindow).DialogResult.HasValue AndAlso DirectCast(sender, InputWindow).DialogResult Then
            If DirectCast(sender, InputWindow).Input = Contexte.UsuariActual.Password Then
                DirectCast(grdBuscador.SelectedItem, LLibreCaixa).DataHoraTancament = Date.SpecifyKind(Now, DateTimeKind.Unspecified)
                Contexte.DomainContext.SubmitChanges(AddressOf FullTancat, Nothing)
                ActivityFullDeCaixa.IsActive = True
            Else
                MessageBox.Show(StringLibrary.PasswordIncorrecte & vbNewLine, StringLibrary.ErrorTancament, MessageBoxButton.OK)
            End If
        End If
    End Sub

    Private Sub FullTancat(ByVal s As SubmitOperation)
        ActivityFullDeCaixa.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.NoPotTancar)
            Contexte.DomainContext.RejectChanges()
        Else
            ProtegirFullDeCaixa(Me.grdBuscador.SelectedItem)
            ProtegirGridReserves(False)
            ProtegirGridDespesesIngressos(False)
        End If
    End Sub

    Private Sub btnTancamentEditar_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As FullDeCaixaTancament
        Child = New FullDeCaixaTancament(grdBuscador.SelectedItem)
        Child.Show()

    End Sub

#End Region

#Region "Reserves"
    Private Sub btnAltaReserva_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As FullDeCaixaReserves = New FullDeCaixaReserves(FullDeCaixaReserves.EnumMode.ModeAlta, New Web.Reserva() With {.LLibreCaixa = grdBuscador.SelectedItem})
        AddHandler Child.Closed, AddressOf FormulariReservesClosed
        Child.Show()
    End Sub
    Private Sub btnModificarReserva_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As FullDeCaixaReserves = New FullDeCaixaReserves(FullDeCaixaReserves.EnumMode.ModeModificacio, Me.grdReserves.SelectedItem)
        AddHandler Child.Closed, AddressOf FormulariReservesClosed
        Child.Show()
    End Sub
    Private Sub btnEliminarReserva_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Try
            If (MessageBox.Show(StringLibrary.DeleteConfirm & vbNewLine, StringLibrary.DeleteTitol, MessageBoxButton.OKCancel) = MessageBoxResult.OK) Then
                Contexte.DomainContext.Reservas.Remove(Me.grdReserves.SelectedItem)
                Contexte.DomainContext.SubmitChanges(AddressOf ReservesDeleted, Nothing)
                ActivityFullDeCaixa.IsActive = True
            End If
        Catch ex As Exception
            App.ShowMessage(ex)
            Contexte.DomainContext.RejectChanges()
        End Try
    End Sub

    Private Sub grdReserves_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdReserves.SelectionChanged
        ProtegirGridReserves(e.AddedItems.Count <> 0)
    End Sub

    Private Sub ProtegirGridReserves(AlgunItemSeleccionat As Boolean)
        If Not AlgunItemSeleccionat Then
            Me.btnEliminarReserva.IsEnabled = False
            Me.btnModificarReserva.IsEnabled = False

            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador OrElse Not DirectCast(grdBuscador.SelectedItem, LLibreCaixa).EsTancat Then
                Me.btnAltaReserva.IsEnabled = True
            Else
                Me.btnAltaReserva.IsEnabled = False
            End If
        Else
            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador OrElse Not DirectCast(grdBuscador.SelectedItem, LLibreCaixa).EsTancat Then
                Me.btnAltaReserva.IsEnabled = True
                Me.btnEliminarReserva.IsEnabled = True
                Me.btnModificarReserva.IsEnabled = True
            Else
                Me.btnAltaReserva.IsEnabled = False
                Me.btnEliminarReserva.IsEnabled = False
                Me.btnModificarReserva.IsEnabled = False
            End If
        End If
    End Sub

    Private Sub FormulariReservesClosed(sender As Object, e As EventArgs)
        Dim Child As FullDeCaixaReserves = DirectCast(sender, FullDeCaixaReserves)

        RemoveHandler Child.Closed, AddressOf FormulariReservesClosed

        ActualitzarDadesGridReserves()
    End Sub

    Private Sub ActualitzarDadesGridReserves()
        Dim FullSeleccionat As LLibreCaixa = DirectCast(grdBuscador.SelectedItem, LLibreCaixa)

        If FullSeleccionat Is Nothing Then
            grdReserves.ItemsSource = Nothing
        Else
            grdReserves.ItemsSource = (From R As Reserva In FullSeleccionat.Reserva Order By R.CodiReserva)
        End If
    End Sub

    Private Sub ReservesDeleted(ByVal s As SubmitOperation)
        ActivityFullDeCaixa.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.NoPotBorrar)
            Contexte.DomainContext.RejectChanges()
        Else
            ActualitzarDadesGridReserves()
            DirectCast(Me.grdBuscador.SelectedItem, Web.LLibreCaixa).ActualitzarCampsCalculats()
        End If
    End Sub
#End Region

#Region "Despesa Ingres"
    Private Sub btnAltaDespesaIngres_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As FullDeCaixaDespesesIngresos = New FullDeCaixaDespesesIngresos(FullDeCaixaDespesesIngresos.EnumMode.ModeAlta, New Web.LLibreCaixaDespesaIngres() With {.LLibreCaixa = grdBuscador.SelectedItem})
        AddHandler Child.Closed, AddressOf FormulariDespesaIngresClosed
        Child.Show()
    End Sub
    Private Sub btnModificarDespesaIngres_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Child As FullDeCaixaDespesesIngresos = New FullDeCaixaDespesesIngresos(FullDeCaixaDespesesIngresos.EnumMode.ModeModificacio, Me.grdDespesesIngressos.SelectedItem)
        AddHandler Child.Closed, AddressOf FormulariDespesaIngresClosed
        Child.Show()
    End Sub
    Private Sub btnEliminarDespesaIngres_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Try
            If (MessageBox.Show(StringLibrary.DeleteConfirm & vbNewLine, StringLibrary.DeleteTitol, MessageBoxButton.OKCancel) = MessageBoxResult.OK) Then
                Contexte.DomainContext.LLibreCaixaDespesaIngres.Remove(Me.grdDespesesIngressos.SelectedItem)
                Contexte.DomainContext.SubmitChanges(AddressOf DespesaIngresDeleted, Nothing)
                ActivityFullDeCaixa.IsActive = True
            End If
        Catch ex As Exception
            App.ShowMessage(ex)
            Contexte.DomainContext.RejectChanges()
        End Try
    End Sub

    Private Sub FormulariDespesaIngresClosed(sender As Object, e As EventArgs)
        Dim Child As FullDeCaixaDespesesIngresos = DirectCast(sender, FullDeCaixaDespesesIngresos)

        RemoveHandler Child.Closed, AddressOf FormulariDespesaIngresClosed

        ActualitzarDadesGridDespesaIngres()
    End Sub

    Private Sub DespesaIngresDeleted(ByVal s As SubmitOperation)
        ActivityFullDeCaixa.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.NoPotBorrar)
            Contexte.DomainContext.RejectChanges()
        Else
            ActualitzarDadesGridDespesaIngres()
            DirectCast(Me.grdBuscador.SelectedItem, Web.LLibreCaixa).ActualitzarCampsCalculats()
        End If
    End Sub

    Private Sub grdDespesesIngressos_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdDespesesIngressos.SelectionChanged
        ProtegirGridDespesesIngressos(e.AddedItems.Count <> 0)
    End Sub

    Private Sub ProtegirGridDespesesIngressos(AlgunItemSeleccionat As Boolean)
        If Not AlgunItemSeleccionat Then
            Me.btnEliminarDespesaIngres.IsEnabled = False
            Me.btnModificarDespesaIngres.IsEnabled = False

            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador OrElse Not DirectCast(grdBuscador.SelectedItem, LLibreCaixa).EsTancat Then
                Me.btnAltaDespesaIngres.IsEnabled = True
            Else
                Me.btnAltaDespesaIngres.IsEnabled = False
            End If
        Else
            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador OrElse Not DirectCast(grdBuscador.SelectedItem, LLibreCaixa).EsTancat Then
                Me.btnAltaDespesaIngres.IsEnabled = True
                Me.btnEliminarDespesaIngres.IsEnabled = True
                Me.btnModificarDespesaIngres.IsEnabled = True
            Else
                Me.btnAltaDespesaIngres.IsEnabled = False
                Me.btnEliminarDespesaIngres.IsEnabled = False
                Me.btnModificarDespesaIngres.IsEnabled = False
            End If
        End If
    End Sub

    Private Sub ActualitzarDadesGridDespesaIngres()
        Dim FullSeleccionat As LLibreCaixa = DirectCast(grdBuscador.SelectedItem, LLibreCaixa)

        If FullSeleccionat Is Nothing Then
            grdDespesesIngressos.ItemsSource = Nothing
        Else
            grdDespesesIngressos.ItemsSource = (From DI As LLibreCaixaDespesaIngres In FullSeleccionat.LLibreCaixaDespesaIngres Order By DI.TipusDespesaIngres.Nom)
        End If
    End Sub

#End Region

#Region "Netejes"
    Private Sub BuscaNeteges(MostrarBarraProgrés As Boolean)

        Me.ActivityNeteja.IsActive = MostrarBarraProgrés

        Dim Data As Date = Date.SpecifyKind(Now.Date, DateTimeKind.Utc)
        Dim Hostals As List(Of Integer) = (From H As Hostal In Contexte.HostalsPerUsuariActual Select H.Id).ToList

        LullabyFullDeCaixa.Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetNetegesPerHostalUsuariIDatesQuery(Hostals, -1, Data, Nothing), _
           New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.Neteja))(AddressOf NetegesLoaded), _
           Nothing)
    End Sub

    Private Sub NetegesLoaded(ByVal LListaNetejes As LoadOperation(Of LullabyFullDeCaixa.Web.Neteja))
        'Un cop carregat ho guardem en una llista
        Me.ActivityNeteja.IsActive = False
        Me.lstNeteges.ItemsSource = (From N As Neteja In LListaNetejes.Entities Order By N.Data Descending, N.Id Descending).ToList()
    End Sub

    Private Sub lstNeteges_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs)
        If e.AddedItems.Count = 0 Then
            Me.btnSortidaNeteja.IsEnabled = False
            Me.btnModificarNeteja.IsEnabled = False
        Else
            Dim Neteja As Neteja = DirectCast(e.AddedItems(0), Neteja)

            Me.btnModificarNeteja.IsEnabled = True
            Me.btnSortidaNeteja.IsEnabled = Not Neteja.EsTancat
        End If
    End Sub

    Private Sub btnEntradaNeteja_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Dim novaNeteja As New LullabyFullDeCaixa.Web.Neteja() With {.Data = Date.SpecifyKind(Now.Date, DateTimeKind.Utc), .HoraObertura = Now.TimeOfDay, .IdUsuariObertura = Contexte.UsuariActual.Id}

            Dim child As New NetejaAltaModificacio(NetejaAltaModificacio.EnumMode.ModeAlta, novaNeteja)
            AddHandler child.Closed, AddressOf NetejaAltaModificacioClosed
            child.Show()
        Else
            Dim child As New NetejaEntradaSortida(NetejaEntradaSortida.EnumMode.ModeEntrada)
            AddHandler child.Closed, AddressOf NetejaEntradaSortidaClosed
            child.Show()
        End If
    End Sub

    Private Sub NetejaAltaModificacioClosed(sender As Object, e As EventArgs)
        Dim child As NetejaAltaModificacio = DirectCast(sender, NetejaAltaModificacio)
        RemoveHandler child.Closed, AddressOf NetejaAltaModificacioClosed
        If child.DialogResult Then BuscaNeteges(True)
    End Sub

    Private Sub NetejaEntradaSortidaClosed(sender As Object, e As EventArgs)
        Dim child As NetejaEntradaSortida = DirectCast(sender, NetejaEntradaSortida)
        RemoveHandler child.Closed, AddressOf NetejaEntradaSortidaClosed
        If child.DialogResult Then BuscaNeteges(True)
    End Sub

    Private Sub btnModificarNeteja_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim child As New NetejaAltaModificacio(NetejaAltaModificacio.EnumMode.ModeModificacio, DirectCast(lstNeteges.SelectedItem, Neteja))
        child.Show()
    End Sub

    Private Sub btnSortidaNeteja_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Dim Neteja As Neteja = DirectCast(lstNeteges.SelectedItem, Neteja)
            Neteja.HoraTancament = Now.TimeOfDay
            Neteja.IdUsuariTancament = Contexte.UsuariActual.Id

            Dim child As New NetejaAltaModificacio(NetejaAltaModificacio.EnumMode.ModeTancament, Neteja)
            child.Show()
        Else
            Dim child As New NetejaEntradaSortida(NetejaEntradaSortida.EnumMode.ModeSortida, DirectCast(lstNeteges.SelectedItem, Neteja))
            child.Show()
        End If
    End Sub



#End Region


    Private Sub Scroll_SizeChanged(sender As System.Object, e As System.Windows.SizeChangedEventArgs)
        Me.Components.MaxHeight = Math.Max(Me.Scroll.ViewportHeight, Me.Components.MinHeight)
        Me.Components.MaxWidth = Math.Max(Me.Scroll.ViewportWidth, Me.Components.MinWidth)
    End Sub



End Class
